//
//  HttpRequest.m
//  TaskManager
//
//  Created by Sun on 2019/3/11.
//  Copyright © 2019 Sun. All rights reserved.
//

#import "HttpRequest.h"

static HttpRequest *shareHttpManager;

@implementation HttpRequest

+ (HttpRequest *)shareManager {
    //线程安全  确保其是唯一的   对象必须全局 或是静态的
    static dispatch_once_t once;
    dispatch_once(&once, ^ {
        shareHttpManager = [[HttpRequest alloc] init];
        shareHttpManager.managerArray = [NSMutableArray array];
    });
    return shareHttpManager;
}

+ (void)configureRequest:(AFHTTPSessionManager *)manager isUpload:(BOOL)isUpload {
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    if ([User isLogin] && [User getUserToken]) {
        [manager.requestSerializer setValue:[User getUserToken] forHTTPHeaderField:@"token"];
    }
    [[HttpRequest shareManager].managerArray addObject:manager];
}

+ (AFHTTPSessionManager *)GetWithApi:(NSString *)url params:(id)dic progress:(RequestProgress)progress success:(RequestSuccess)success fail:(RequestFail)fail {
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:BaseUrl]];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [self configureRequest:manager isUpload:NO];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *urlstr = [url containsString:BaseUrl] ? url : [NSString stringWithFormat:@"%@%@",BaseUrl,url];
        NSMutableDictionary *mutDic = [NSMutableDictionary dictionaryWithDictionary:dic];
        NSLog(@"GET请求的参数:%@",mutDic);
        [manager GET:urlstr parameters:mutDic progress:progress success:^(NSURLSessionDataTask *operation, id responseObject) {
            [[HttpRequest shareManager].managerArray removeObject:manager];
            [self verifyRequestValue:operation params:mutDic responseObject:responseObject progress:progress success:success failure:fail post:NO];
        }failure:^(NSURLSessionDataTask *operation, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hidenHUD];
                if ([HttpRequest shareManager].managerArray.count) {
                    fail(error);
                    [[HttpRequest shareManager].managerArray removeObject:manager];
                }
//                [MBProgressHUD leShowFailedHUD:MAIN_WINDOW message:@"您的网络不给力哦"];
            });
        }];
    });
    return manager;
}

+ (AFHTTPSessionManager *)PostWithApi:(NSString *)url params:(id)dic progress:(RequestProgress)progress success:(RequestSuccess)success fail:(RequestFail)fail {
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:BaseUrl]];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [self configureRequest:manager isUpload:NO];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //拼接链接
        NSString *urlstr = ([url containsString:@"http:"]||[url containsString:@"https:"])?url:[NSString stringWithFormat:@"%@%@",BaseUrl,url];
        NSMutableDictionary *mutDic = [NSMutableDictionary dictionaryWithDictionary:dic];
        NSLog(@"请求参数--%@",mutDic);
        NSLog(@"请求--%@",urlstr);
        //发起请求
        [manager POST:urlstr parameters:mutDic progress:progress success:^(NSURLSessionDataTask *operation, id responseObject) {
            //成功回调
            [MBProgressHUD hidenHUD];
            [[HttpRequest shareManager].managerArray removeObject:manager];
            //处理成功的数据
            [self verifyRequestValue:operation params:[FactoryMethod stringWithJSONData:mutDic] responseObject:responseObject progress:progress success:success failure:fail post:YES];
        }failure:^(NSURLSessionDataTask *operation, NSError *error) {
            //失败回调
            [MBProgressHUD hidenHUD];
            dispatch_async(dispatch_get_main_queue(), ^{
                fail(error);
                if ([HttpRequest shareManager].managerArray.count) {
                    [[HttpRequest shareManager].managerArray removeObject:manager];
                }
//                [MBProgressHUD leShowFailedHUD:MAIN_WINDOW message:@"您的网络不给力哦"];
            });
        }];
    });
    return manager;
}

+ (AFURLSessionManager *)PostJsonWithApi:(NSString *)url params:(id)dic progress:(RequestProgress)progress success:(RequestSuccess)success fail:(RequestFail)fail {
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:@"" parameters:nil error:nil];
    request.timeoutInterval= 10;
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    if ([User isLogin] && [User getUserToken]) {
        [request setValue:[User getUserToken] forHTTPHeaderField:@"token"];
    }
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"application/xml",@"text/plain",@"application/xhtml+xml", @"text/json",@"multipart/form-data", @"text/javascript",@"text/html", @"text/xml",@"image/jpeg",@"image/png",@"application/x-www-form-urlencoded", nil];
    manager.responseSerializer  = responseSerializer;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *urlstr = ([url containsString:@"http:"]||[url containsString:@"https:"])?url:[NSString stringWithFormat:@"%@%@",BaseUrl,url];
        NSMutableDictionary *mutDic = [NSMutableDictionary dictionaryWithDictionary:dic];
        NSLog(@"请求参数--%@",mutDic);
        NSData *JSONdata = [NSData data];
        JSONdata = [[FactoryMethod toJSONString:mutDic] dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableURLRequest *jsonRequest = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlstr parameters:nil error:nil];
        jsonRequest.timeoutInterval = 10;
        [jsonRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        // 设置body
        [jsonRequest setHTTPBody:JSONdata];
        [[manager dataTaskWithRequest:jsonRequest uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
            
        } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
            
        } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
            if (!error) {
                [MBProgressHUD hidenHUD];
                //处理成功的数据
                [self verifyJsonRequestValue:nil params:mutDic responseObject:responseObject progress:progress success:success failure:fail post:YES];
            }else {
                [MBProgressHUD hidenHUD];
                dispatch_async(dispatch_get_main_queue(), ^{
                    fail(error);
                    if ([HttpRequest shareManager].managerArray.count) {
                        [[HttpRequest shareManager].managerArray removeObject:manager];
                    }
//                    [MBProgressHUD leShowFailedHUD:MAIN_WINDOW message:@"您的网络不给力哦"];
                });
            }
        }] resume];
    });
    return manager;
}

+ (AFHTTPSessionManager *)noDismissHudPostWithApi:(NSString *)url params:(id)dic progress:(RequestProgress)progress success:(RequestSuccess)success fail:(RequestFail)fail {
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:BaseUrl]];
    // 请求方式是 Json
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [self configureRequest:manager isUpload:NO];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //拼接链接
        NSString *urlstr = ([url containsString:@"http:"]||[url containsString:@"https:"])?url:[NSString stringWithFormat:@"%@%@",BaseUrl,url];
        NSMutableDictionary *mutDic = [NSMutableDictionary dictionaryWithDictionary:dic];
        //发起请求
        [manager POST:urlstr parameters:[FactoryMethod stringWithJSONData:mutDic] progress:progress success:^(NSURLSessionDataTask *operation, id responseObject) {
            //成功回调
            [[HttpRequest shareManager].managerArray removeObject:manager];
            //处理成功的数据
            [self verifyRequestValue:operation params:[FactoryMethod stringWithJSONData:mutDic] responseObject:responseObject progress:progress success:success failure:fail post:YES];
        }failure:^(NSURLSessionDataTask *operation, NSError *error) {
            //失败回调
            dispatch_async(dispatch_get_main_queue(), ^{
                fail(error);
                if ([HttpRequest shareManager].managerArray.count) {
                    [[HttpRequest shareManager].managerArray removeObject:manager];
                }
//                [MBProgressHUD leShowFailedHUD:MAIN_WINDOW message:@"您的网络不给力哦"];
            });
        }];
    });
    return manager;
}

+ (void)PostUploadImgWithApi:(NSString *)url params:(NSString *)dicStr success:(RequestSuccess)success dail:(RequestFail)fail {
    NSString *urlstr = ([url containsString:@"http:"]||[url containsString:@"https:"])?url:[NSString stringWithFormat:@"%@%@",BaseUrl,url];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //1.创建会话对象
        NSURLSession *session = [NSURLSession sharedSession];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlstr]];
        request.HTTPMethod = @"POST";
        request.HTTPBody = [dicStr dataUsingEncoding:NSUTF8StringEncoding];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            //8.解析数据
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            if (!error) {
                [self verifyRequestValue:nil params:dicStr responseObject:dict progress:nil success:success failure:fail post:YES];
            }else {
                //失败回调
                dispatch_async(dispatch_get_main_queue(), ^{
                    fail(error);
//                    [MBProgressHUD leShowFailedHUD:MAIN_WINDOW message:@"您的网络不给力哦"];
                });
            }
        }];
        //7.执行任务
        [dataTask resume];
    });
}

+ (AFHTTPSessionManager *)postImgWithUrl:(NSString *)url imglist:(NSArray *)imglist imgFile:(NSString *)imgFile withParameter:(NSDictionary *)dic sucess:(RequestSuccess)sucessCallBack failure:(RequestFail)failureCallBack {
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:BaseUrl]];
    // 请求方式是 Json
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [self configureRequest:manager isUpload:NO];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //拼接链接
        NSString *urlstr = ([url containsString:@"http:"]||[url containsString:@"https:"])?url:[NSString stringWithFormat:@"%@%@",BaseUrl,url];
        NSMutableDictionary *mutDic = [NSMutableDictionary dictionaryWithDictionary:dic];
        NSLog(@"请求参数--%@",mutDic);
        [manager POST:urlstr parameters:mutDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            [imglist enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSData *data = UIImageJPEGRepresentation(obj, 1);
//                 NSData *data = UIImagePNGRepresentation(obj);
                 [formData appendPartWithFileData:data name:imgFile fileName:[NSString stringWithFormat:@"%@.jpg",imgFile] mimeType:@"image/png"];
            }];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [MBProgressHUD hidenHUD];
            [self verifyRequestValue:task params:[FactoryMethod stringWithJSONData:mutDic] responseObject:responseObject progress:nil success:sucessCallBack failure:failureCallBack post:YES];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [MBProgressHUD hidenHUD];
            dispatch_async(dispatch_get_main_queue(), ^{
                failureCallBack(error);
                if ([HttpRequest shareManager].managerArray.count) {
                    [[HttpRequest shareManager].managerArray removeObject:manager];
                }
//                [MBProgressHUD leShowFailedHUD:MAIN_WINDOW message:@"您的网络不给力哦"];
            });
        }];
    });
    return manager;
}

+ (AFHTTPSessionManager *)postImgDataWithUrl:(NSString *)url imgData:(NSData *)imgData imgFile:(NSString *)imgFile withParameter:(NSDictionary *)dic sucess:(RequestSuccess)sucessCallBack failure:(RequestFail)failureCallBack {
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:BaseUrl]];
    // 请求方式是 Json
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [self configureRequest:manager isUpload:NO];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //拼接链接
        NSString *urlstr = ([url containsString:@"http:"]||[url containsString:@"https:"])?url:[NSString stringWithFormat:@"%@%@",BaseUrl,url];
        NSMutableDictionary *mutDic = [NSMutableDictionary dictionaryWithDictionary:dic];
        NSLog(@"请求参数--%@",mutDic);
        [manager POST:urlstr parameters:mutDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            if (imgData) {
                [formData appendPartWithFileData:imgData name:imgFile fileName:[NSString stringWithFormat:@"%@.jpg",imgFile] mimeType:@"image/png"];
            }
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [MBProgressHUD hidenHUD];
            [self verifyRequestValue:task params:[FactoryMethod stringWithJSONData:mutDic] responseObject:responseObject progress:nil success:sucessCallBack failure:failureCallBack post:YES];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [MBProgressHUD hidenHUD];
            dispatch_async(dispatch_get_main_queue(), ^{
                failureCallBack(error);
                if ([HttpRequest shareManager].managerArray.count) {
                    [[HttpRequest shareManager].managerArray removeObject:manager];
                }
//                [MBProgressHUD leShowFailedHUD:MAIN_WINDOW message:@"您的网络不给力哦"];
            });
        }];
    });
    return manager;
}

/**
 验证请求成功之后的返回值
 
 @param operation 上次的请求
 @param dict 请求参数
 @param responseObject 上次请求成功之后的参数
 @param success 外部调用的 block
 @param failblock <#failblock description#>
 @param post 是否是post请求
 */
+ (void)verifyRequestValue:(NSURLSessionDataTask *)operation params:(id)dict responseObject:(id)responseObject progress:(RequestProgress)progress success:(RequestSuccess)success failure:(RequestFail)failblock post:(BOOL)post{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSInteger errorCode = [responseObject[@"code"] integerValue];
        if (errorCode == 1) {
            //请求成功，接口调用成功
            success(operation,responseObject[@"data"],1,errorCode);
        }else {
            if (errorCode == 8000) {
                //未登录
                [User logoutSuccess];
                NSString *errorMessage = [responseObject objectForKey:@"msg"];
                success(operation, errorMessage, 0, errorCode);
                [MBProgressHUD leShowFailedHUD:MAIN_WINDOW message:errorMessage];
            }else if (errorCode == 20014) {
                //抢单失败
                success(operation,responseObject,1,errorCode);
            }else {
                //请求成功，接口调用失败
                NSString *errorMessage = [responseObject objectForKey:@"msg"];
                success(operation, errorMessage, 0, errorCode);
                [MBProgressHUD leShowFailedHUD:MAIN_WINDOW message:errorMessage];
            }
        }
    });
}

+ (void)verifyJsonRequestValue:(NSURLSessionDataTask *)operation params:(id)dict responseObject:(id)responseObject progress:(RequestProgress)progress success:(RequestSuccess)success failure:(RequestFail)failblock post:(BOOL)post{
    id jsonData = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
    dispatch_async(dispatch_get_main_queue(), ^{
        NSInteger errorCode = [jsonData[@"code"] integerValue];
        if (errorCode == 1) {
            //请求成功，接口调用成功
            success(operation,jsonData[@"data"],1,errorCode);
        }else {
            //请求成功，接口调用失败
            NSString *errorMessage = [jsonData objectForKey:@"msg"];
            success(operation, errorMessage, 0, errorCode);
            [MBProgressHUD leShowFailedHUD:MAIN_WINDOW message:errorMessage];
        }
    });
}

+ (void)checkNetworkStatus {
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                [MBProgressHUD leShowFailedHUD:MAIN_WINDOW message:@"网络信号不佳或网络未连接，请检查网络"];
                break;
            case AFNetworkReachabilityStatusNotReachable:
                [MBProgressHUD leShowFailedHUD:MAIN_WINDOW message:@"网络信号不佳或网络未连接，请检查网络"];
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {

            }
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {

            }
                break;
            default:
                break;
        }
    }];
}

+ (NSInteger)getNetworkStatus {
    /*
     AFNetworkReachabilityStatusUnknown          = -1,未知
     AFNetworkReachabilityStatusNotReachable     = 0,无连接
     AFNetworkReachabilityStatusReachableViaWWAN = 1,流量
     AFNetworkReachabilityStatusReachableViaWiFi = 2,wifi
     */
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    AFNetworkReachabilityStatus networkStatus = [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus;
    return networkStatus;
}

@end
